import { parse } from 'querystring';
import pathRegexp from 'path-to-regexp';

/* eslint no-useless-escape:0 import/prefer-default-export:0 */
export const isAntDesignPro = () => {
  if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return true;
  }

  return window.location.hostname === 'preview.pro.ant.design';
}; // 给官方演示站点用，用于关闭真实开发环境不需要使用的特性

export const isAntDesignProOrDev = () => {
  const { NODE_ENV } = process.env;

  if (NODE_ENV === 'development') {
    return true;
  }

  return isAntDesignPro();
};

/**
 * props.route.routes
 * @param router [{}]
 * @param pathname string
 */
export const getAuthorityFromRouter = (router = [], pathname) => {
  const authority = router.find(
    ({ routes, path = '/' }) =>
      (path && pathRegexp(path).exec(pathname)) ||
      (routes && getAuthorityFromRouter(routes, pathname)),
  );
  if (authority) return authority;
  return undefined;
};

export const getRouteAuthority = (path, routeData) => {
  let authorities;
  routeData.forEach(route => {
    // match prefix
    if (pathRegexp(`${route.path}/(.*)`).test(`${path}/`)) {
      if (route.authority) {
        authorities = route.authority;
      } // exact match

      if (route.path === path) {
        authorities = route.authority || authorities;
      } // get children authority recursively

      if (route.routes) {
        authorities = getRouteAuthority(path, route.routes) || authorities;
      }
    }
  });
  return authorities;
};

/**
 * 清除cookie
 * @param {*} cname 
 */
export function clearCookie(cname) {
  setCookie(cname, '', -1);
};

/**
 * 获取cookie
 * @param {*} cname 
 */
export function getCookie(cname) {
  const name = ((window.config.systemName || '') + cname) + '=';
  const ca = document.cookie.split(';');
  for (let i = 0; i < ca.length; i++) {
    const c = ca[i];
    while (c.charAt(0) === ' ') c = c.substring(1);
    if (c.indexOf(name) !== -1) return c.substring(name.length, c.length);
  }
  return '';
}

/**
 * 判断是否url
 * @param {*} path 
 */
export function isUrl(path) {
  const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;
  return reg.test(path);
}

/**
 * 获取url请求参数
 */
export function getUrlParameters() {
  return parse(window.location.href.split('?')[1]);
}

/**
 * 设置cookie
 * @param {*} cname 
 * @param {*} cvalue 
 * @param {*} expire 
 */
export function setCookie(cname, cvalue, expire, path = '/') {
  const d = new Date();
  if (expire) {
    d.setTime(d.getTime() + expire);
  }
  document.cookie = ((window.config.systemName || '') + cname) + '=' + cvalue + ((expire == null) ? '' : ';expires=' + d.toUTCString()) + ";path=" + path;
}

export function filter(data, value, field, isSubSelected) {
  if (value && Array.isArray(data)) {
    return data.filter((item) => {
      if (!isSubSelected) {
        if (Array.isArray(field) && field.length > 0) {
          let flag = false;
          field.forEach(f => {
            if (item && item[f] && item[f].toLowerCase().includes(value.toLowerCase())) {
              flag = true;
            }
          });
          return flag;
        } else {
          return item && item[field] && item[field].toLowerCase().includes(value.toLowerCase());
        }
      } else {
        if (item['children'] && Array.isArray(item['children']) && item['children'].length > 0) {
          const children = item['children'].filter(child => child && child[field] && child[field].toLowerCase().includes(value.toLowerCase()));
          if (children && children.length > 0) {
            item.children = children;
            return item;
          } else {
            return false;
          }
        } else {
          return item && item[field] && item[field].toLowerCase().includes(value.toLowerCase());
        }
      }
    });
  }
  return data;
}
